package com.example.demo.gateway.filter.web;

import com.example.demo.gateway.support.ReactiveRequestContextHolder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.core.publisher.SignalType;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/4/15 20:26
 * @Description:
 */
@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class ContextFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getRawPath();
        if (path.contains("favicon.ico")) {
            return exchange.getResponse().setComplete();
        }
        ReactiveRequestContextHolder.put(request);
        return chain.filter(exchange).doFinally(signalType -> {
            if (SignalType.ON_COMPLETE == signalType) {
                ReactiveRequestContextHolder.remove();
                System.out.println("清除完成");
            }
        });
        //.subscriberContext(ctx -> ctx.put(ReactiveRequestContextHolder.CONTEXT_KEY, request));
    }
}
